package com.yang.mall.tools;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

public class JWTUtils {



    private final static Logger logger = LoggerFactory.getLogger(JWTUtils.class);

    public final static String base64Secret = "fruit2019";


    public static boolean checkToken(String token,String userId){

        if(StringUtils.isEmpty(token)){
            return false;
        }

        if (token.equals("abc123") ){

            return true;

        }

        Claims claims =  JWTUtils.parseJWT(token);


        if (claims==null){

            logger.error("解密失败:"+userId);
            logger.error("token:"+token);

            return false;

        }

        String parseUser = (String)claims.get("memberId");

        if (userId.equals(parseUser)){

            return true;
        }

        return false;



    }


    /**
     * 解析jwt
     */
    public static Claims parseJWT(String jsonWebToken) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(base64Secret))
                    .parseClaimsJws(jsonWebToken).getBody();

            return claims;

        } catch (Exception ex) {

            logger.error("Exception:"+ ex.getMessage());
            return null;
        }
    }

    /**
     * 构建jwt
     */
    public static String createJWT(String userId, long TTLMillis) {

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .claim("memberId", userId)
                .signWith(signatureAlgorithm, signingKey);
        //添加Token过期时间
        if (TTLMillis >= 0) {
            long expMillis = nowMillis + TTLMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp).setNotBefore(now);
        }

        //生成JWT
        return builder.compact();
    }

//    /**
//     * 构建jwt
////     */
//    public static String createToken(String userId,long TTLMillis) {
//        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
//
//        long nowMillis = System.currentTimeMillis();
//        Date now = new Date(nowMillis);
//
//        //生成签名密钥
//        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret);
//        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
//
//        //添加构成JWT的参数
//        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
//                .claim("userId", userId)
//                .signWith(signatureAlgorithm, signingKey);
//        //添加Token过期时间
//        if (TTLMillis >= 0) {
//            long expMillis = nowMillis + TTLMillis;
//            Date exp = new Date(expMillis);
//            builder.setExpiration(exp).setNotBefore(now);
//        }
//
//        //生成JWT
//        return builder.compact();
//    }

}